//Created by Roman Clarkson for Jaws.Core.Web
//Original work Copyright(C) 2008.  All Rights Reserved.

using System.Collections;
using System.Xml;
using System.Xml.Serialization;

namespace Jaws.Core.Web.Data
{
    public class EntityListBase<C, T> : ArrayList
        where T : IXmlSerializable, IEntityBase, new()
        where C : IXmlSerializable, new()
    {
        public new T this[int index]
        {
            get { return (T) base[index]; }
            set { base[index] = value; }
        }

        public int Add(T value)
        {
            for (int i = 0; i < Count; i++)
            {
                if (this[i].Id == value.Id)
                    return Count + 1;
            }
            return base.Add(value);
        }


        public void GetChildObjects(XmlReader reader)
        {
            while (reader.Read() && reader.NodeType == XmlNodeType.Element)
            {
                var subObject = new T();
                subObject.ReadXml(reader);
                Add(subObject);
            }
        }

        public void SaveChildObjects(XmlWriter writer)
        {
            foreach (T resource in this)
            {
                resource.WriteXml(writer);
            }
        }
    }
}